package com.my.hotel.util;

import com.my.hotel.entity.Log;
import com.my.hotel.entity.User;
import com.my.hotel.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class LogManager {

    @Autowired
    private LogService logService;

    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("切面类，增强方法");
        Log log = new Log();
        Object proceed = pjp.proceed();
        // 通过 pjp 拿到方法签名
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        // 通过方法签名拿到被调用的方法
        Method method = methodSignature.getMethod();
        //获取注解   用户删除方法
        ILog iLog = method.getAnnotation(ILog.class);
        //如果注解不为空，则为添加日志操作的数据
        if(iLog!=null){
            //获取注解的value值
            String value = iLog.value();
            //获取当前系统时间 以yyyy-MM-dd HH:mm:ss
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            log.setOptTime(sdf.format(date));
            //获取request对象
            ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            //获取session对象 并获取登录用户信息
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("userinfo");
            //设置操作日志的用户
            log.setOptId(user.getId());
            //获取方法参数
            Object[] args = pjp.getArgs();
            //设置日志信息
            String msg=user.getUsername()+value+",操作数据"+Arrays.toString(args);
            log.setOptContent(msg);
            //添加日志
            logService.addLog(log);
        }
        return proceed;
    }
}
